package com.itheima.bos.web.action.take_delivery;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;

import com.itheima.bos.domain.take_delivery.Promotion;
import com.itheima.bos.service.take_delivery.IPromotionService;
import com.itheima.bos.web.action.common.BaseAction;

public class PromotionAction extends BaseAction<Promotion> {

	// 注入业务层
	@Autowired
	private IPromotionService promotionService;

	// 属性驱动，获取标题文件
	private File titleImgFile;
	private String titleImgFileFileName;

	public void setTitleImgFile(File titleImgFile) {
		this.titleImgFile = titleImgFile;
	}

	public void setTitleImgFileFileName(String titleImgFileFileName) {
		this.titleImgFileFileName = titleImgFileFileName;
	}

	// 保存宣传任务
	@Action(value = "promotion_save", results = { @Result(name = "success", location = "/pages/take_delivery/promotion.html", type = "redirect") })
	public String save() throws IOException {
		// 宣传图片上传路径
		String savePath = ServletActionContext.getServletContext().getRealPath(
				"/upload/");
		String saveUrl = ServletActionContext.getRequest().getContextPath()
				+ "/upload/";

		// 使用uuid生成随机图片名
		UUID uuid = UUID.randomUUID();
		String ext = titleImgFileFileName.substring(titleImgFileFileName
				.lastIndexOf("."));
		String randomFileName = uuid + ext;
		// 保存图片
		File destFile = new File(savePath + "/" + randomFileName);
		FileUtils.copyFile(titleImgFile, destFile);

		// 保存url路径到数据库中
		model.setTitleImg(saveUrl + randomFileName);

		// 调用业务层，保存数据
		promotionService.save(model);

		return SUCCESS;
	}

	@Action(value = "promotion_pageQuery", results = { @Result(name = "success", type = "json") })
	public String pageQuery() {
		// 封装分页查询
		Pageable pageable = new PageRequest(page - 1, rows);
		// 调用业务层，得到pageData对象
		Page<Promotion> pageData = promotionService.pageQuery(pageable);
		//将pageData对象压入值栈
		pushPageDataToValueStack(pageData);
		return SUCCESS;
	}
}
